/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufes.ceunes.poo.model.dao;

import br.ufes.ceunes.poo.model.pojo.Cliente;
import br.ufes.ceunes.poo.util.JPAUtil;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

/**
 *
 * @author Igor
 */
public class ClienteDAO implements DAOGenerico<Cliente, Integer> {

    @Override
    public void salvar(Cliente objeto) {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        EntityTransaction tx = JPAUtil.getInstance().getTransaction(em);
        em.persist(objeto);
        tx.commit();
        em.close();
    }

    @Override
    public void remover(Cliente objeto) {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.remove(objeto);
        tx.commit();
        em.close();
    }

    @Override
    public List<Cliente> listar() {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        Query query = em.createQuery("select c from Cliente c", Cliente.class);
        List lista = query.getResultList();
        em.close();
        return lista;
    }

    public List<Cliente> buscarPorNome(String nome) {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        Query query = em.createQuery("select cliente from Cliente cliente where"
                + " cliente.nome like '%" + nome + "%'", Cliente.class);
        List lista = query.getResultList();
        em.close();
        return lista;
    }

    @Override
    public Cliente buscarPorId(Integer id) {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        return em.find(Cliente.class, id);
    }

    public List<Cliente> buscarPorCpf(String cpf) {
        EntityManager em = JPAUtil.getInstance().getEntityManager();
        Query query = em.createQuery("select c from Cliente c where c.cpf"
                + "like :cpf",
                Cliente.class);
        query.setParameter("cpf", cpf);
        return query.getResultList();
    }

}
